﻿package test;

import hapi.web.RouteManager;
import haxe.unit.TestCase;

class TestRouteManager extends TestCase {

	var manager:RouteManager<String>;
	
	override function setup() {
		manager = new RouteManager();
		manager.map("/models", "ListModels");
		manager.map("/models/:id/show", "ShowModel");
		manager.map("/models/new", "CreateModel");
		manager.map("/models/list", "ListModels");
		manager.map("/differentModel/:id/children/edit", "EditModelChildren");
		manager.map("/differentModel/:name/:subname/edit", "EditModelByName");
		manager.map("/:uri", "404");
	}
	
	public function testNotFound() {
		assertEquals("404", manager.from("/unknown_url").value);
	}
	
	public function testWithSlashAtEnd() {
		assertEquals("404", manager.from("/unknown_url/").value);
	}
	
	public function testSimple() {
		var t:Dynamic = { };
		t.value = "test";
		Reflect.setField(t, "a", "a");
		assertEquals("test", t.value);
		assertEquals("a", t.a);
	}
	
	public function testToStatic() {
		assertEquals("/models", manager.to("ListModels"));
	}
	
	public function testToShow() {
		assertEquals("/models/7/show", manager.to("ShowModel", {id:7}));
	}
	
	public function testToUnknow() {
		assertEquals("", manager.to("Unknow", {id:7}));
	}
	
	public function testToNew() {
		assertEquals("/models/new", manager.to("CreateModel"));
	}
	
	public function testToDifferent() {
		assertEquals("/differentModel/gumbas/children/edit", manager.to("EditModelChildren", {id:"gumbas"}));
	}
	
	public function testFromStatic() {
		assertEquals("ListModels", manager.from("/models").value);
		assertTrue(Reflect.fields(manager.from("/models").params).length == 0);
	}
	
	public function testFromNew() {
		assertEquals("CreateModel", manager.from("/models/new").value);
		assertTrue(Reflect.fields(manager.from("/models/new").params).length == 0);
	}
	
	public function testFromShow() {
		assertEquals("ShowModel", manager.from("/models/7/show").value);
		assertEquals('7', manager.from("/models/7/show").params.id);
	}
	
	public function testFromUnknow() {
		assertEquals(null, manager.from("/models/7/show/unknow").value);
		assertTrue(Reflect.fields(manager.from("/models/7/show/unknow").params).length == 0);
	}
	
	public function testFromDifferent() {
		assertEquals("EditModelChildren", manager.from("/differentModel/gumbas/children/edit").value);
		assertEquals("gumbas", manager.from("/differentModel/gumbas/children/edit").params.id);
	}
	
	public function testMultipleParamsNoId() {
		assertEquals("EditModelByName", manager.from("/differentModel/gumbas/ula/edit").value);
		assertEquals("gumbas", manager.from("/differentModel/gumbas/ula/edit").params.name);
		assertEquals("ula", manager.from("/differentModel/gumbas/ula/edit").params.subname);
		assertEquals(null, manager.from("/differentModel/gumbas/ula/edit").params.id);
	}
}